<template>
  <div v-if="postVoList.length >= 1" class="postDetail">
    <div class="top">
      <h1 class="title">主题：{{ postVoList[0].title }}</h1>
      <div class="buttons">
        <el-button-group>
          <el-button size="mini" icon="el-icon-caret-top" type="primary" :plain="postVoList[0].isLike === 0?false:true" @click.stop="handleLike(postVoList[0])">喜欢</el-button>
          <el-button size="mini" icon="el-icon-caret-bottom" type="danger" :plain="postVoList[0].isLike === 1?false:true" @click.stop="handleDislike(postVoList[0])">不喜欢</el-button>
        </el-button-group>
        <div class="other-button">
          <span class="collect" @click.stop="handleCollect(postVoList[0])"><i :class="postVoList[0].isCollect === 0?'el-icon-star-on':'el-icon-star-off'" />收藏</span>
          <span class="report" @click.stop="handleReport(postVoList[0])"><i class="el-icon-warning-outline" />举报</span>
        </div>
      </div>
    </div>
    <postReplyCard
      v-for="(item, index) in postReplyList"
      :key="item.id"
      :post-reply="item"
      :order="index + 1"
      :is-focus="userFocusInfoMap[item.userInfo.id]?userFocusInfoMap[item.userInfo.id].isFocus:undefined"
      @updatePostReplyVoList="updatePostReplyVoList"
      @updateUserFocusInfoList="updateUserFocusInfoList"
    />
    <div>
      <Editor
        v-model="replyContent"
        class="editor"
        api-key="no-api-key"
        :init="editInit"
      />
      <div class="bottom">
        <el-button type="primary" plain :loading="isPublishReplyButtonLoading" @click="handlePublishReply">发表回复</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import postReplyCard from '@/components/postReplyCard'
import Editor from '@tinymce/tinymce-vue'
import { getPostReplyVoList, savePostReply } from '@/api/postReply'
import { getPostVoList } from '@/api/post'
import { savePostFeedback, updatePostFeedback } from '@/api/postfeedback'
import { getUserFocusInfoList } from '@/api/userFocusInfo'
import { upload } from '@/api/upload'
import pubsub from 'pubsub-js'
import { formatDateTime } from '@/utils/dateUtil'
export default {
  name: 'PostDetail',
  components: {
    postReplyCard,
    Editor
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      replyContent: '',
      postId: this.$route.query.postId,
      postVoList: [],
      postReplyList: [],
      pageNum: 1,
      pageSize: 10,
      isPublishReplyButtonLoading: false,
      editInit: {
        language: 'zh_CN',
        statusbar: false,
        plugins: 'image',
        images_upload_handler: (blobInfo, success, failure) => {
          // 创建一个 FormData 对象
          var formData = new FormData()
          // 将要上传的图片文件添加到 FormData 中
          formData.append('file', blobInfo.blob())
          upload(formData).then(res => {
            this.replyContent += `<img src='${this.baseUrl + res.data.imageUrl}'/>`
            success('')
          }, err => {
            console.log(err)
            failure('')
          })
        }
      },
      pubsubId: undefined,
      userFocusInfoMap: {}
    }
  },
  beforeMount() {
    this.getPostVoList()
    this.getPostReplyVoList()
    this.subscribeUpdatePostReplyVoList()
    this.getUserFocusInfoList()
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubsubId)
  },
  methods: {
    updateUserFocusInfoList() {
      this.getUserFocusInfoList()
    },
    getUserFocusInfoList() {
      getUserFocusInfoList().then(res => {
        const userFocusInfoList = res.data
        this.userFocusInfoMap = userFocusInfoList?.reduce((cur, value) => {
          cur[value.beFocusedUserId] = value
          return cur
        }, {})
        this.userFocusInfoMap = this.userFocusInfoMap ? this.userFocusInfoMap : {}
      }, err => {
        console.log(err)
      })
    },
    subscribeUpdatePostReplyVoList() {
      this.pubsubId = pubsub.subscribe('updateData', () => {
        this.pageSize += 10
        this.getPostReplyVoList()
      })
    },
    async handlePublishReply() {
      if (!this.replyContent) {
        this.$message({
          message: '请输入回复内容',
          type: 'warning'
        })
        return
      }
      this.isPublishReplyButtonLoading = true
      var regexp = new RegExp(`<img src="${this.baseUrl.replace('/', '')}`, 'gi')
      const postReply = {
        postId: this.postVoList[0].id,
        content: this.replyContent.replace(regexp, `<img src="`),
        publishDate: formatDateTime(new Date())
      }
      await savePostReply(postReply)
      this.getPostReplyVoList()
      this.replyContent = ''
      this.isPublishReplyButtonLoading = false
    },
    updatePostReplyVoList() {
      this.getPostReplyVoList()
    },
    async getPostVoList() {
      const searchParam = {
        pageNum: 1,
        pageSize: 5,
        searches: [
          {
            key: 'post.id',
            rule: '=',
            value: this.postId
          }
        ]
      }
      const { data } = await getPostVoList(searchParam)
      this.postVoList = data.list
    },
    async getPostReplyVoList() {
      const searchParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searches: [
          {
            key: 'post_id',
            rule: '=',
            value: this.postId
          }
        ]
      }
      const { data } = await getPostReplyVoList(searchParam)
      this.postReplyList = data.list
    },
    async handleLike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleDislike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 1
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleCollect(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isCollect: postInfo.isCollect === 0 ? 1 : 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    handleReport(postInfo) {
      this.$router.push({
        path: '/report',
        query: {
          postId: postInfo.id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.postDetail {
  margin: 10px auto;
  width: 1300px;
  background: rgba(133, 185, 254, 0.738);
  border-radius: 20px;
  padding: 10px 20px;
  .top {
    background-color: white;
    padding: 10px;
    border-bottom: 1px solid rgb(203, 203, 203);
    display: flex;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    .title {
      margin: 0;
      font-size: 25px;
      flex-grow: 1;
      font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    }
    .buttons {
      flex-shrink: 0;
      .other-button {
        display: inline-block;
        margin-left: 10px;
        color: gray;
        font-size: 13px;
        span {
          margin-right: 10px;
        }
        span:hover {
          cursor: pointer;
        }
      }
    }
  }
  .editor {
    height: 380px;
  }
  .el-pagination {
    background-color: white;
    padding: 10px 0;
    text-align: center;
  }
  .bottom {
    background-color: white;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
    text-align: right;
    padding: 10px;
  }
}
</style>
